package cn.q3c.parse.impl.smzdm;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.text.SimpleDateFormat;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.time.DateFormatUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.apache.log4j.Logger;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;

import cn.keyvalue.ccf.common.object.DetailPage;
import cn.keyvalue.ccf.common.object.Hyperlink;
import cn.keyvalue.ccf.common.object.Image;
import cn.q3c.parse.base.BaseParse;

/**
 * 什么值得买页面解析
 * @author wangxinning
 *
 */
public class SmzdmIndexParseImpl implements BaseParse {

	private static final Logger logger = Logger
			.getLogger(SmzdmIndexParseImpl.class);

	public Object parse(String url, File file, String abouturl, File aboutFile) {

		try {
			Document doc = Jsoup.parse(FileUtils.readFileToString(file));
			doc.setBaseUri(url);

			// 标准元素获取
			String title = doc.title();
			String description = doc.select("meta[name=description]").attr(
					"content");
			String keywords = doc.select("meta[name=keywords]").attr("content");
			DetailPage page = new DetailPage();
			page.setUrl(url);
			page.setTitle(StringUtils.trimToEmpty(title));
			page.setDescription(StringUtils.trimToEmpty(description));
			page.setKeywords(StringUtils.trimToEmpty(keywords));

			// 页面导航
			List<Hyperlink> crumbs = new ArrayList<Hyperlink>();
			Elements elements = doc.select("div[class=crumbBox]").select("a");
			for (int i = 0; i < elements.size(); i++) {
				Hyperlink link = new Hyperlink();
				link.setName(elements.get(i).text());
				link.setTitle(elements.get(i).attr("title"));
				link.setUrl(elements.get(i).attr("abs:href"));
				crumbs.add(link);
			}
			if (!crumbs.isEmpty()) {
				page.setCrumbs(crumbs);
			}

			// 分类
			List<Hyperlink> types = new ArrayList<Hyperlink>();
			Elements tagelements = doc.select("div[class=classified]").select(
					"a");
			for (int i = 0; i < tagelements.size(); i++) {
				Hyperlink link = new Hyperlink();
				link.setName(tagelements.get(i).text());
				link.setTitle(tagelements.get(i).attr("title"));
				link.setUrl(tagelements.get(i).attr("abs:href"));
				types.add(link);
			}
			if (!types.isEmpty()) {
				page.setTypes(types);
			}

			// 内容标题
			String contenttitle = doc.select("h1[class=con_title]").text();
			page.setBodytitle(StringUtils.trimToEmpty(contenttitle));

			// 发表时间
			String dateTime = doc.select("div[class=dateTime]").text();
			if (StringUtils.isNotBlank(dateTime)) {
				// 跨年问题，因为没有年份，最多有一天的时差
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");

				// 当前时间
				long current = System.currentTimeMillis();
				long parseDate = sdf.parse(
						DateFormatUtils.format(current, "yyyy") + "-"
								+ dateTime).getTime();

				if (parseDate > current) {
					page.setDatetime(sdf.parse((NumberUtils
							.toInt(DateFormatUtils.format(current, "yyyy")) - 1)
							+ "-" + dateTime));
				} else {
					page.setDatetime(new Date(parseDate));
				}
			}

			// 内容，遇到p填入换行标记
			Elements bodyElements = doc.select("div[class=conBox]").select("p");			
			String bodyStr = "";
			// 内容中的图片
			List<Image> images = new ArrayList<Image>();
			for (int i = 0; i < bodyElements.size(); i++) {
				String tempLine = bodyElements.get(i).text();
				bodyStr += "<!--b-->" + tempLine + "<!--/b-->";

				// 判断图片
				Elements imgElements = bodyElements.get(i).select("img");
				if (imgElements != null && !imgElements.isEmpty()) {
					for (int z = 0; z < imgElements.size(); z++) {
						Image img = new Image();
						img.setSrc(imgElements.get(z).attr("abs:src"));
						img.setAlt(imgElements.get(z).attr("alt"));// alt
						img.setWidth(NumberUtils.toInt(imgElements.get(z).attr(
								"width")));
						img.setHeight(NumberUtils.toInt(imgElements.get(z)
								.attr("height")));
						images.add(img);
					}
				}
			}
			page.setBody(bodyStr);
			if (!images.isEmpty()) {
				page.setImages(images);
			}

			// 直达链接
			Hyperlink jumpLink = new Hyperlink();
			Elements zhidaElements = doc.select("div[class=zhida_more]")
					.select("a");
			Elements zhidaElements2 = doc.select("div[class=zhida]")
					.select("a");
			zhidaElements.addAll(zhidaElements2);
			if (zhidaElements != null && !zhidaElements.isEmpty()) {
				jumpLink.setUrl(zhidaElements.get(0).attr("abs:href"));
				page.setNextHyperlink(jumpLink);
			}

			// 标签
			List<Hyperlink> tags = new ArrayList<Hyperlink>();
			tagelements = doc.select("span[class=classified]").select("a");
			for (int i = 0; i < tagelements.size(); i++) {
				Hyperlink link = new Hyperlink();
				link.setName(tagelements.get(i).text());
				link.setTitle(tagelements.get(i).attr("title"));
				link.setUrl(tagelements.get(i).attr("abs:href"));
				tags.add(link);
			}
			// 标签尾部加入商城信息
			Hyperlink link = new Hyperlink();
			String shopname = doc.select("span[class=from_val]").text();
			link.setName(shopname);
			if (StringUtils.isNotBlank(shopname)) {
				link.setName(shopname);
				tags.add(link);
			}
			if (!tags.isEmpty()) {
				page.setTags(tags);
			}

			//返回内容打印
			logger.debug("page:" + page);

			return page;

		} catch (Exception e) {

			logger.error("解析什么值得买详情页异常", e);
		}

		return null;
	}
}